/**
 * User: Obi
 * Date: 02.08.11
 * Time: 22:06
 */
package com.jediflasher.game_client {
	import com.jediflasher.game_client.controller.LoginController;
	import com.jediflasher.game_client.controller.UniverseController;
	import com.jediflasher.game_client.data.LoginData;
	import com.jediflasher.game_client.data.UniverseData;
	import com.jediflasher.game_client.events.model.LoginDataEvent;
	import com.jediflasher.game_client.server.ServerConnector;
	import com.jediflasher.game_client.utils.logging.Logger;
	import com.jediflasher.game_client.view.BaseView;
	import com.jediflasher.game_client.view.LoginView;
	import com.jediflasher.game_client.view.UniverseView;

	import flash.display.Sprite;
	import flash.text.TextField;

	public class GameInitializer extends Sprite {

		private static const PORT:int = 7181;
		public static const POLICY_PORT:int = 7180;

		private static const HOST:String = "172.22.1.116";

		public function GameInitializer() {
			Logger.log("GameInitializer::");
			this._sc = new ServerConnector(HOST, PORT, POLICY_PORT);
			Logger.log("Server connector created: host:"+HOST +" port:"+PORT);

			var loginData:LoginData = new LoginData();
			loginData.addEventListener(LoginDataEvent.LOGIN_SUCCESS, this.handler_loginSuccess);

			var loginView:LoginView = new LoginView(loginData);
			this._loginController = new LoginController(this._sc, loginData, loginView);

			super.addChild(loginView);
		}

		/**
		 * private
		 */
		private var _sc:ServerConnector;

		/**
		 * @private
		 */
		private var _loginController:LoginController;

		/**
		 * @private
		 */
		private var _universeController:UniverseController;

		/**
		 * private
		 */
		private var _tf:TextField;

		private function createWorld(userId:int):void {
			var universeData:UniverseData = new UniverseData(userId);
			var universeView:UniverseView = new UniverseView(universeData);
			super.addChild(universeView);

			this._universeController = new UniverseController(this._sc, universeData, universeView);
		}

		/**
		 * @private
		 */
		private function handler_loginSuccess(event:LoginDataEvent):void {
			Logger.log("Login success");
			var loginView:BaseView = this._loginController.view;
			super.removeChild(loginView);

			var userId:int = (this._loginController.data as LoginData).id;
			this.createWorld(userId);
		}
	}
}
